package com.domor.framework.jwt.interceptor;

import com.domor.common.exception.TokenException;
import com.domor.framework.jwt.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @Desc: token验证拦截器
* @Author: liyuyang
* @Date: 2020/6/31
**/
@Slf4j
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 获取请求头信息authorization信息
        final String authHeader = request.getHeader(JwtTokenUtil.AUTH_HEADER_KEY);

        if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
            log.info("auth Exception: user not login, no token");
            throw new TokenException("Token Exception: user not login");
        }

        // 获取token
        final String token = authHeader.substring(7);

        // 验证token是否有效--无效已做异常抛出，由全局异常处理后返回对应信息
        JwtTokenUtil.parseJWT(token);
        request.setAttribute("loginUser", JwtTokenUtil.getUsername(token));
        request.setAttribute("loginRoleKey", JwtTokenUtil.getRoleKey(token));
        request.setAttribute("loginDeptId", JwtTokenUtil.getDeptId(token));

        return true;
    }

}
